#include <iostm8s103f3.h>
#include <intrinsics.h>

unsigned int Led = 0;

int main( void )
{
  // setup clock
  CLK_CKDIVR &= (unsigned char)(~0x18);  // 16MHz high speed internal clock
  
  //LED: B5
  PB_DDR |= 0x20;  // output
  PB_CR1 |= 0x20;  // push pull
  PB_CR2 |= 0x20;  // 10MHz output speed
  
  // setup timer 2; generate a 5Hz(0.2s) interrupt
  TIM2_PSCR = 0x08;   // prescaler = 256; 16MHz/(2^8)=62500Hz
  TIM2_ARRH = 0x30;   // high byte of 12499(12500-1)
  TIM2_ARRL = 0xD3;   // low byte of 12499(12500-1)
  TIM2_IER = 0x01;    // update interrupts enabled
  TIM2_CR1 = 0x01;    // enable the timer
  
  // enable interrupt
  __enable_interrupt();
  
  while (1) {
    
  }
}


//  Timer 2 Overflow handler.
#pragma vector = TIM2_OVR_UIF_vector
__interrupt void TIM2_OVR_UIF_IRQHandler(void)
{
  if (Led == 0) {
    Led = 1;
    PB_ODR |= 0x20;     // HIGH if OFF
    TIM2_ARRH = 0xC3;   // high byte of 49999(50000-1)
    TIM2_ARRL = 0x4F;   // low byte of 49999(50000-1)
  }
  else {
    Led = 0;
    PB_ODR &= 0xDF;     // LOW is ON
    TIM2_ARRH = 0x30;   // high byte of 12499(12500-1)
    TIM2_ARRL = 0xD3;   // low byte of 12499(12500-1)
  }
  
  TIM2_SR1 &= 0xFE;
}
